package com.guguskins.back.common.interceptor;

import com.guguskins.back.common.annotation.Authorized;
import com.guguskins.back.common.enums.ResultStatusEnum;
import com.guguskins.back.common.exception.GlobaStatusException;
import com.guguskins.back.entity.GuUser;
import com.guguskins.back.service.GuUserService;
import com.guguskins.back.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @date 2021/5/21 11:44
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private GuUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求是否属于方法的请求
        if(handler instanceof HandlerMethod) {
            HandlerMethod  method = (HandlerMethod) handler;
            if (method.getMethodAnnotation(Authorized.class) != null) {
                String token = request.getHeader("token");
                if (ObjectUtils.isEmpty(token)) {

                    throw new GlobaStatusException(ResultStatusEnum.UNAUTHORIZED);
                } else {
                    try {
                        Long userId = JwtUtil.verifyToken(token).get("userId", Long.class);
                        GuUser user = userService.getById(userId);
                        if (ObjectUtils.isEmpty(user)) {
                            throw new RuntimeException();
                        }
                    } catch (Exception exception) {
//                        throw new GlobalHttpStatusException(HttpResponseEnum.UNAUTHORIZED);
                        throw new GlobaStatusException(ResultStatusEnum.UNAUTHORIZED);
                    }
                }
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
